# handle_search_flickr.py - Handle queue requests to search flickr.
# Copyright 2010 Rob Myers <rob@robmyers.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import datetime
import datastore
import logging
import simplejson
import traceback

import search_flickr

import wsgiref.handlers
from google.appengine.runtime import DeadlineExceededError
from google.appengine.ext import webapp

try:
    from google.appengine.api.taskqueue import Task
except:
    from google.appengine.api.labs.taskqueue import Task

class FlickrSearchWorker(webapp.RequestHandler):
    def get_photo(self, dgr_yaml_path, terms):
        result = None
        photos = search_flickr.search(terms)
        if photos:
            for photo in photos:
                photo_post_data = search_flickr.to_post_data(photo)
                if not datastore.AlreadyPostedUrl(dgr_yaml_path, 'flickr',
                                                  photo_post_data.source_url):
                    result = photo_post_data
                    break
        return result

    def post(self):
        dgr_yaml_path = self.request.get('dgr-yaml-path')
        dgr_run_time_string = self.request.get('dgr-run-time')
        dgr_run_time = datetime.datetime.\
            fromtimestamp(float(dgr_run_time_string))
        emotions_json = self.request.get('emotions')
        #emotions = simplejson.loads(emotions_json)
        terms = simplejson.loads(self.request.get('terms'))
        if(dgr_yaml_path and len(terms) > 0):
            try:
                logging.info('flickr search ' + dgr_yaml_path + ' ' + \
                                 str(terms))
                photo = self.get_photo(dgr_yaml_path, terms)
                if (photo):
                    datastore.StorePostData(dgr_yaml_path, dgr_run_time, 
                                            "flickr", photo)
                    dgr_task = Task(url='/post-broadcast', method='POST',
                                    params={'dgr-yaml-path': dgr_yaml_path,
                                            'emotions': emotions_json,
                                            'post-data': photo.as_json()})
                    dgr_task.add('broadcast-queue')
                    logging.info('Success -> ' + str(photo))
                else:
                    logging.info('No flickr match')
            except Exception, e:
                logging.error(type(e))
                logging.error(e)
                logging.error(traceback.format_exc())

def main():
    wsgiref.handlers.CGIHandler().run(webapp.WSGIApplication([
                ('/search-flickr', FlickrSearchWorker)], debug=True))
    
if __name__ == '__main__':
    logging.getLogger().setLevel(logging.DEBUG)
    main()
